<template>
  <div class="page-wrap">
    <!-- <Modal
        v-model="editModal.show"
        :title="editModal.title"
        :loading="editModal.loading"
        :mask-closable="false"
        width="1120px"
    > -->
    <!-- <div style="color: rgb(27, 76, 184); margin-bottom: 15px">
      <div class="addressIcon"></div>
      <span>当前位置：</span>
      <span style="cursor: pointer" @click="returnCourse">{{ pageTitle }}管理</span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="color: #333">{{ titleText }}</span>
    </div> -->
    <div class="page-content" :style="{ height: contentHei }">
      <div class="img-header">
        <div style="font-weight: 700; font-size: 18px">
          {{ titleText }}
<!--          <RadioGroup-->
<!--            v-if="!ecid"-->
<!--            style="margin-left: 40px"-->
<!--            v-model="formValidate.expType"-->
<!--            type="button"-->
<!--            button-style="solid"-->
<!--            @on-change="changeExpType"-->
<!--          >-->
<!--            <Radio :label="0">实操课件</Radio>-->
<!--            <Radio :label="1">理论课件</Radio>-->
<!--            <Radio :label="2">文本课件</Radio>-->
<!--          </RadioGroup>-->
        </div>
      </div>
      <Divider />
      <div class="content-wrap">
        <StepList
          :data="stepList"
          :current="currentStep"
          @change-step="gotoStep"
          style="margin-bottom: 20px"
        ></StepList>
        <Form
          v-if="currentStep === 1"
          ref="formValidate"
          :model="formValidate"
          :rules="ruleValidate"
          :label-width="95"
        >
          <Row>
            <Col span="10">
              <FormItem :label="pageLittleTitle+'名称'" prop="name">
                <Input
                  v-model.trim="formValidate.name"
                  placeholder='名称不能包含下列任意英文字符 \ / : * ? " < > |，长度为1-128个字符'
                ></Input>
              </FormItem>
              <FormItem label="方向" prop="direction">
                <i-select
                  v-model="formValidate.direction"
                  placeholder="方向"
                  @on-change="changeDirection"
                >
                  <i-option
                    v-for="(value, key) in expClassifyLevel1"
                    :value="value.dictid"
                    :key="key"
                    >{{ value.dictname }}</i-option
                  >
                </i-select>
              </FormItem>
              <FormItem label="类型" prop="type">
                <i-select v-model="formValidate.type" placeholder="类型">
                  <i-option
                    v-for="(value, key) in expClassifyLevel2"
                    :value="value.dictid"
                    :key="key"
                    >{{ value.dictname }}</i-option
                  >
                </i-select>
              </FormItem>
              <FormItem label="标签" prop="labels">
                <Select filterable
                  v-model="formValidate.labels"
                  placeholder="标签"
                  multiple
                  :max-tag-count="1"
                >
                  <Option
                    v-for="(value, key) in expClassifyTag"
                    :value="value.dictname"
                    :key="key"
                    >{{ value.dictname }}</Option
                  >
                </Select>
                <!-- <Button type="primary" ghost @click="selectExp">选择标签</Button> -->
                <Icon
                  type="md-add"
                  size="17"
                  color="#a8a6c8"
                  @click="addLabelsModal = true"
                  class="add_icon"
                />
                <!-- <span>
						<WarningTip content="只能添加一个标签，重复添加的话，会清空原来添加的标签" width="800"></WarningTip>
						</span> -->
                <Tag
                  closable
                  v-for="(item, index) in mergeLabels"
                  :key="index"
                  :title="item"
                  @on-close="handleCloseTag(item)"
                  class="flex_ba width_150"
                  >{{ item }}</Tag
                >
              </FormItem>
              <FormItem label="课时" prop="hours">
                <InputNumber
                  :min="1"
                  :step="1"
                  :max="999"
                  v-model="formValidate.hours"
                ></InputNumber>
              </FormItem>
              <FormItem label="难度" prop="difficulty">
                <RadioGroup v-model="formValidate.difficulty">
                  <Radio label="Simple">简单</Radio>
                  <Radio label="Medium">中等</Radio>
                  <Radio label="Hard">较难</Radio>
                </RadioGroup>
              </FormItem>
              <FormItem :label="pageLittleTitle+'用途'" prop="selfType">
                <RadioGroup v-model="formValidate.selfType">
                  <Radio :label="Number(value)" v-for="(label,value)  in selftypeMap" :key="value">{{label}}</Radio>
                </RadioGroup>
              </FormItem>
              <!-- <FormItem label="可见范围" prop="public">
                                <RadioGroup v-model="formValidate.public" @on-change="changePublic">
                                    <Radio label="1">单位</Radio>
                                    <Radio label="0">个人</Radio>
                                </RadioGroup>
                                <span
                                    v-if="!isCreate"
                                    style="color:#f90;position:absolute;white-space: nowrap;"
                                >
                                    <Icon
                                        type="ios-information-circle"
                                    />可见范围由个人编辑为单位时，课件使用的个人资源(工程模板、指导书、视频、课件、图片、题目)的可见范围将变为单位</span
                                >
                            </FormItem> -->
              <FormItem label="描述" prop="desc">
                <Input
                  v-model.trim="formValidate.desc"
                  type="textarea"
                  :maxlength="200"
                  :autosize="{ minRows: 2, maxRows: 5 }"
                  placeholder="描述"
                ></Input>
              </FormItem>
              <FormItem label="封面图片" prop="topology" v-show="showImgItem">
                <Button
                  type="primary"
                  @click="
                    searchFileName = '';
                    searchFilePublic = '';
                    videoPage = 1;
                    getVideoList('images');
                  "
                  >选择</Button
                >
                <UploadFile
                  bucket="images"
                  :public="formValidate.public"
                  @on-success="getUrlAndSaveType"
                  ref="imageUpload"
                ></UploadFile>
                <div class="chose-wrap" v-show="formValidate.topology != ''">
                  <div class="flex" style="flex: auto">
                    <!--<img src="../../assets/exper/guide.png" class="chose-s2-icon">-->
                    <div class="chose-name">
                      <img
                        :src="handleImage(useImagePath)"
                        style="
                          display: inline-block;
                          height: 40px;
                          width: auto;
                          vertical-align: middle;
                        "
                      />
                    </div>
                  </div>
                  <img
                    src="../../../../assets/globalIcon/dis-del.png"
                    style="width: 13px; height: 14px; cursor: pointer"
                    @click="clearImg"
                  />
                </div>
              </FormItem>
            </Col>
            <Col span="10" offset="1">
              <FormItem
                label="工程模板"
                prop="envtempid"
                class="template-lable"
                v-if="formValidate.expType == 0"
              >
                <div class="template-select-wrapper">
                  <div class="select-type-wrapper">
                    <div
                      class="type"
                      v-for="(type, index) in edit.templateSelectType"
                      :key="type.value"
                      :class="
                        edit.curSelectType === type.value ? 'current' : ''
                      "
                      @click="handChangeSelectType(type.value)"
                    >
                      {{ type.title }}
                    </div>
                  </div>
                  <div class="select-content-wrapper">
                    <template v-if="edit.curSelectType === 'projectTemplate'">
                      <Button
                        class="template-type w150"
                        :type="
                          edit.curTemplateType == '0' ? 'primary' : 'default'
                        "
                        @click="refreshTem('0')"
                      >
                        普通模板
                      </Button>
<!--                      <Button-->
<!--                        class="template-type w150"-->
<!--                        :type="-->
<!--                          edit.curTemplateType == 'base' ? 'primary' : 'default'-->
<!--                        "-->
<!--                        @click="refreshTem('base')"-->
<!--                      >-->
<!--                        基础模板-->
<!--                      </Button>-->
                    </template>
                    <template v-if="edit.curSelectType === 'image'">
                      <GenerateTemplate
                          :devicetype = "formValidate.deviceBaseType"
                        @on-success="getTemplateInfoImage"
                      ></GenerateTemplate>
                    </template>
                    <template v-if="edit.curSelectType === 'exper'">
                      <ExperTemplate
                        @on-select="getTemplateInfo"
                      ></ExperTemplate>
                    </template>
                    <template v-if="edit.curSelectType === 'upload'">
                      <ImportTemplate
                        :public="formValidate.public"
                        @on-success="getTemplateInfo"
                      ></ImportTemplate>
                    </template>
                  </div>
                </div>
                <!-- <Button type="primary" ghost @click="refreshTem()">选择</Button> -->
                <div class="chose-wrap" v-show="formValidate.envtempid" style="height:32px">
                  <div class="flex" style="flex: auto">
                    <img
                      src="../../../../assets/exper/template.png"
                      class="chose-s-icon"
                    />
                    <Tooltip :content="formValidate.envtempid" placement="top" max-width="300">
                        <div class="chose-name" style="margin-top: 12px">{{ formValidate.envtempid }}</div>
                    </Tooltip>
                  </div>
                  <img
                    src="../../../../assets/globalIcon/dis-del.png"
                    style="width: 13px; height: 14px; cursor: pointer"
                    @click="clearTemp"
                  />
                </div>
              </FormItem>

<!--              <FormItem-->
<!--                  label="关联实物设备"-->
<!--                  prop="customType"-->
<!--                  :class="{-->
<!--                  'template-lable': formValidate.expType == 0 ? true : false,-->
<!--                }"-->
<!--                  -->
<!--              >-->
<!--                <RadioGroup-->
<!--                    v-model="formValidate.relaDevice"-->
<!--                    @on-change="changeGuideType"-->
<!--                >-->
<!--                  <Radio :label="1">是</Radio>-->
<!--                  <Radio :label="0">否</Radio>-->
<!--                </RadioGroup>-->
<!--              </FormItem>-->

<!--              <FormItem-->
<!--                  v-if="formValidate.relaDevice != 0"-->
<!--                  label="实物设备类型"-->
<!--                  prop="deviceBaseType"-->
<!--              >-->
<!--                <i-select-->
<!--                    clearable-->
<!--                    filterable-->
<!--                    placeholder="请选择实物设备类型"-->
<!--                    v-model="formValidate.deviceBaseType"-->
<!--                >-->
<!--                  <i-option :value="item.dictCode" v-for="(item,idx) in deviceTypes" :key="item.dictCode">{{item.dictCnCode}}</i-option>-->
<!--                -->
<!--                </i-select>-->
<!--                -->
<!--                -->
<!--              </FormItem>-->
              
              <FormItem
                label="指导书类型"
                prop="customType"
                :class="{
                  'template-lable': formValidate.expType == 0 ? true : false,
                }"
                v-if="formValidate.expType != 2"
              >
                <RadioGroup
                  v-model="formValidate.customType"
                  @on-change="changeGuideType"
                >
                  <Radio :label="0">标准类型</Radio>
                  <Radio :label="1">文档类型</Radio>
                </RadioGroup>
              </FormItem>
              <FormItem
                label="指导书"
                prop="guide"
                :class="{
                  'template-lable': formValidate.expType == 0 ? true : false,
                }"
                v-if="formValidate.expType != 2"
              >
                <Button type="primary" @click="refreshFile()">选择</Button>
                <UploadFile
                  bucket="docs"
                  ref="guideUpload"
                  :public="formValidate.public"
                  @on-success="
                    (data) => {
                      return getUrl(data, 'guide');
                    }
                  "
                  v-if="formValidate.customType === 1"
                >
                </UploadFile>
                <CreateGuide
                  @on-success="getGuideInfo"
                  v-if="formValidate.customType === 0"
                ></CreateGuide>
                <ImportGuide
                  @on-success="getGuideInfo"
                  :public="formValidate.public"
                  v-if="formValidate.customType === 0"
                ></ImportGuide>
                <div class="chose-wrap" v-show="formValidate.guide">
                  <div class="flex" style="flex: auto">
                    <img
                      src="../../../../assets/exper/guide.png"
                      class="chose-s2-icon"
                    />
                    <div class="chose-name">{{ formValidate.guide }}</div>
                  </div>
                  <img
                    src="../../../../assets/globalIcon/dis-del.png"
                    style="width: 13px; height: 14px; cursor: pointer"
                    @click="clearGuide"
                  />
                </div>
              </FormItem>
              <FormItem
                label="视频"
                prop="video"
                v-if="formValidate.expType != 2"
              >
                <Button
                  type="primary"
                  @click="
                    searchFileName = '';
                    searchFilePublic = '';
                    videoPage = 1;
                    getVideoList('videos');
                  "
                  >选择</Button
                >
                <UploadFile
                  bucket="videos"
                  @on-success="getUrl"
                  ref="videoUpload"
                  :public="formValidate.public"
                >
                </UploadFile>
                <div class="chose-wrap" v-show="expVideo != ''">
                  <div class="flex" style="flex: auto">
                    <img
                      src="../../../../assets/exper/guide.png"
                      class="chose-s2-icon"
                    />
                    <div class="chose-name">{{ expVideo.originName }}</div>
                  </div>
                  <img
                    src="../../../../assets/globalIcon/dis-del.png"
                    style="width: 13px; height: 14px; cursor: pointer"
                    @click="clearVideo"
                  />
                </div>
              </FormItem>
              <FormItem
                label="课件文件"
                prop="video"
              >
                <Button
                  type="primary"
                  @click="
                    searchFileName = '';
                    searchFilePublic = '';
                    videoPage = 1;
                    getVideoList('courseware');
                  "
                  >选择</Button
                >
                <UploadFile
                  bucket="courseware"
                  @on-success="getUrl"
                  ref="coursewareUpload"
                  :public="formValidate.public"
                >
                </UploadFile>
                <div class="chose-wrap" v-show="expDoc != ''">
                  <div class="flex" style="flex: auto">
                    <img
                      src="../../../../assets/exper/guide.png"
                      class="chose-s2-icon"
                    />
                    <div class="chose-name">{{ expDoc.originName }}</div>
                  </div>
                  <img
                    src="../../../../assets/globalIcon/dis-del.png"
                    style="width: 13px; height: 14px; cursor: pointer"
                    @click="clearDoc"
                  />
                </div>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div v-if="currentStep == 2 && formValidate.expType === 0">
          <DeployExper
            ref="imageList"
            :ecId="ecid"
            :ecName="formValidate.name"
            :templateId="useTemplateId"
            @on-finish="setEnvironStepFinishStatus"
          ></DeployExper>
        </div>
        <div
          v-if="
            (currentStep == 3 && formValidate.expType === 0) ||
            (formValidate.expType !== 0 && currentStep == 2)
          "
        >
          <ExpQuestion
            :ecId="ecid"
            :isOwn="true"
            :isPublic="formValidate.isPublic"
            :status="false"
            @on-finish="setQuestionStepFinishStatus"
          ></ExpQuestion>
        </div>
        <div class="flex-end">
          <!-- <Button @click="submitBtn('formValidate', 2)" v-if="currentStep === 1"
                        >保存</Button
                    > -->
          <Button
            v-if="currentStep !== 1"
            type="primary"
            class="ml10"
            @click="switchStep('prev')"
            >上一步</Button
          >
          <Button
            v-if="showNextBtn"
            type="primary"
            class="ml10"
            @click="switchStep('next')"
            >下一步</Button
          >
          <Button class="ml10" @click="returnList">返回列表页</Button>
          <!-- <Button
                                    @click="handleReset('formValidate')"
                                    style="margin-left: 8px"
                                    ></Button
                                > -->
        </div>
      </div>
    </div>
    <!-- </Modal> -->
    <!--工程模板-->
    <DrawerPage
        select
        v-model="addDeviceModel"
        title="工程模板"
        :columns="templateCol"
        :data="templateList"
        :total="templateTotal"
        :size.sync="templatePageSize"
        :page.sync="templatePage"
        :loading="proTemLoading"
        @queryFun="toPlateTabs"
    >
        <ResourseUsageIllustrate type="课件" v-if="false" slot="rule"></ResourseUsageIllustrate>
        <template slot="search">
            <i-select
              clearable
              placeholder="请选择可见范围"
              v-model="selectProTemModel"
              @on-change="changeTemplate"
            >
              <i-option value="range">平台</i-option>
              <i-option value="system">系统</i-option>
              <i-option value="company">单位</i-option><i-option value="person">个人</i-option>
            </i-select>
            <Input
              v-model.trim="searchTemNameInput"
              placeholder="模板名称"
              clearable
              @on-change="searchTemNameBtn"
            />
            <Button
              class="header-btn"
              type="primary"
              @click="refreshTem(edit.curTemplateType)"
              ><i class="el-icon-refresh-right"
            /></Button>
        </template>
    </DrawerPage>
    <!--指导书-->
    <DrawerPage
      select
      title="指导书"
      v-model="guideModal"
      :columns="expGuideListCol"
      :data="expGuideList"
      :total="expGuideTotal"
      :loading="guideLoading"
      :page.sync="expGuidePage"
      :size.sync="expGuidePageSize"
      @queryFun="showGuideBtn"
    >
        <ResourseUsageIllustrate type="课件" slot="rule" v-if="false"></ResourseUsageIllustrate>
        <template slot="search">
            <i-select
              clearable
              v-model="shareStatus"
              placeholder="请选择可见范围"
              @on-change="changeType"
            >
              <i-option value="2">系统</i-option>
              <i-option value="1">单位</i-option>
              <i-option value="0">个人</i-option>
            </i-select>
            <Input
              v-model.trim="searchGuideInput"
              placeholder="指导书名称"
              clearable
              @on-change="searchGuideBtn"
            />
            <Button class="header-btn" type="primary" @click="refreshFile()"
              ><i class="el-icon-refresh-right"
            /></Button>
        </template>
    </DrawerPage>
    <!--图片列表-->
    <DrawerPage
        select
        v-model="imgModal"
        :title="imgDrawerTitle"
        :columns="getShowVideoCol()"
        :data="videoList"
        :loading="fileListLoading"
        :total="videoTotal"
        :size.sync="videoPageSize"
        :page.sync="videoPage"
        @queryFun="getVideoList(selectType)"
    >
      <ResourseUsageIllustrate type="课件" slot="rule" v-if="false"></ResourseUsageIllustrate>
      <template slot="search">
            <i-select
              clearable
              v-model="searchFilePublic"
              placeholder="请选择可见范围"
              @on-change="searchFile"
            >
              <i-option value="range">平台</i-option>
              <i-option value="system">系统</i-option>
              <i-option value="company">单位</i-option><i-option value="person">个人</i-option>
            </i-select>
            <Input
              v-model.trim="searchFileName"
              :placeholder="imgDrawerSearchPlaceholder"
              clearable
              @on-change="searchFile"
            />
            <Button class="header-btn" type="primary" @click="refreshImg()"
              ><i class="el-icon-refresh-right"
            /></Button>
      </template>
    </DrawerPage>
    <EditGuide
      v-model="editGuideModal.show"
      :data="editGuideModal.data"
      type="update"
      @close="searchGuideData"
    ></EditGuide>
    <!-- 添加标签 -->
    <Modal
      v-model="addLabelsModal"
      title="添加标签"
      @on-ok="submitLabels"
      @on-cancel="cancelLabels"
    >
      <Input
        v-model.trim="addLabels"
        placeholder="请输入标签"
        style="width: 95%"
        :maxlength='64'
      />
      <WarningTip content="请输入个数为1-64的字符"></WarningTip>
      <div slot="footer">
        <Button @click="cancelLabels" type="text">取消</Button>
        <Button @click="submitLabels" type="primary" :disabled="!addLabels"
          >确定</Button
        >
      </div>
    </Modal>
    <!-- 添加标签 -->
    <Modal
      v-model="addExpModal"
      title="添加标签"
      @on-ok="submitLabelsSave"
      @on-cancel="cancelLabelsSave"
    >
      <!-- <Select filterable v-model="formValidate.labels" placeholder="标签" multiple :max-tag-count="1" style="width: 470px;">
						<Option v-for="(value,key) in expClassifyTag" :value="value.dictname" :key="key">{{value.dictname}}</Option>
				</Select> -->
      <div style="margin-top: 20px; width: 470px; display: flex">
        <Input
          v-model.trim="addLabels"
          placeholder="请输入标签"
          :maxlength="64"
        />
        <Button
          type="primary"
          ghost
          style="margin-left: 10px"
          @click="submitLabels"
          >添加</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {createIcon,getIconData} from '@/api/icon.js'
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import replaceTemplateMixin from './mixins/replace-template';
import { experType ,getSelLabelType,dictEntrysSave,dictEntrysSaveBatch} from '@/api/dict.js';
import {
  getDeviceType,
    submitExper,
    modifyExper,
    experimentDetail,
    experStatus,
    getCreateImageList
} from '@/api/selfStudy/courseExp.js';
import { getTemplateData, getTempInfpByID } from '@/api/proTemplate.js';
import { getGuideData, getGuideInfoByID, getGuideInfoByID_new } from '@/api/guide.js';
import defaultImg from '@/assets/globalIcon/course.jpg';
import closeIcon from '@/assets/globalIcon/closeIcon.png';
//  import {imgList} from '@/api/guide.js'
import {
    addExpVideo,
    delExpVideo,
    modifyExpVideo,
    clearExpVideo,
    getVideoDetail,
    queryExpQuestion
} from '@/api/selfStudy/courseExp.js';
import { getFilesData } from '@/api/uploadFile.js';
import ResourseUsageIllustrate from '@/components/resourse-usage-illustrate';
import StepList from '@/components/step-list';
import GenerateTemplate from './components/generate-template';
import ExperTemplate from './components/exper-template';
import UploadFile from './components/upload';
import CreateGuide from './guide/create-modal';
import EditGuide from './guide/edit-modal';
import ImportGuide from './guide/import-guide';
import DeployExper from './environ/deployExper';
import SaveExper from './environ/saveExper';
import ExpQuestion from './question/expQuestion';
import ImportTemplate from './components/import-template';
import {mapGetters, mapState} from 'vuex';
import { validateName128 } from '@/libs/reg'
export default {
    name: 'CreateExper',
    components: {
        ResourseUsageIllustrate,
        StepList,
        GenerateTemplate,
        ExperTemplate,
        UploadFile,
        CreateGuide,
        EditGuide,
        ImportGuide,
        DeployExper,
        SaveExper,
        ExpQuestion,
        ImportTemplate
    },
    mixins: [replaceTemplateMixin],
    data() {
        const validateHour = (rule, value, callback) => {
            let val = parseInt(value);
            if (val > 0 && val <= 999) {
                callback();
            } else {
                callback(new Error('请输入课时为1——999'));
            }
        };
        const validateTemId = (rule, value, callback) => {
            console.log(value);
        };
        //			const validateName = (rule, value, callback) => { //验证只能填入数字
        //				var reg = new RegExp("^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$");
        //				//验证警戒值
        //				if(value) {
        //					if(!reg.test(value)) {
        //						callback(new Error('请输入中文、数字、字母、下划线、-'));
        //					} else {
        //						callback()
        //					}
        //				} else {
        //					callback()
        //				}
        //			}
        const validateName = (rule, value, callback) => {
            var reg = /[\\\:：*?？"”<>|;；，,+=]/gi;
            //验证警戒值
            if (value) {
                if (reg.test(value)) {
                    callback(new Error('名称不能包含下列任意字符 \\ : * ? " < > | ; , + ='));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        let _this = this;
        return {
            // 用户信息
            userName: '',
            USER_ID: '',
            // 页面设置
            defaultImg,
            closeIcon,
            fullHeight: document.documentElement.clientHeight,
            fullWidth: document.documentElement.clientWidth,
            contentHei: 'auto',
            upLoadIconUrl: `${this.baseURL}/virtual/icon/fileUpload`,
            editModal: {
                show: false,
                loading: true,
                title: '创建培训'
            },
            editGuideModal: {
                show: false,
                loading: true,
                title: '编辑指导书'
            },
            mdGuideEditModal: {
                show: false,
                loading: true,
                title: '编辑指导书'
            },
            typeName: '',
            edit: {
                templateSelectType: [
                    {
                        title: '工程模板',
                        value: 'projectTemplate'
                    },
                    {
                        title: '镜像选择',
                        value: 'image'
                    },
                    {
                        title: '课件选择',
                        value: 'exper'
                    },
                    {
                        title: '导入模板',
                        value: 'upload'
                    }
                ],
                curSelectType: 'projectTemplate',
                curTemplateType: 0
            },
            // 先判断状态
            isCreate: true,
            receiveData: {},
            showImgItem: true,
            ecid: '',
            // 页面标题
            titleText: '',
            // 表单
          
            selftypeMap:{
              0:'培训',
              1:'自学',
              2:'通用',
            },
          deviceTypes:[],
            formValidate: {
                name: '',
                direction: '',
                type: '',
                labels: [],
                hours: 1,
                difficulty: 'Simple',
                public: '0',
                desc: '',
                envtempid: '',
                guide: '',
                topology: '',
              deviceBaseType:'',
                relaDevice:0,
                expType: 0, //0.实操课件 、1.理论课件、2.文本课件 ,
                customType: 0, //0.数据、1.文档文件
                selfType: 0 //是否用于自学  0 培训  1 自学  2 通用
            },
            ruleValidate: {
                name: [
                    {
                        required: true,
                        max: 128,
                        message: '课件名称长度为1—128个字符',
                        trigger: 'change'
                    },
                    {
                        validator: validateName128,
                        trigger: 'change'
                    }
                ],
                type: [
                    {
                        required: true,
                        message: '类型不能为空',
                        trigger: 'change'
                    }
                ],
                direction: [
                    {
                        required: true,
                        message: '方向不能为空',
                        trigger: 'change'
                    }
                ],
                hours: [
                    {
                        required: true,
                        validator: validateHour,
                        trigger: 'change'
                    }
                ],
                difficulty: [
                    {
                        required: true,
                        message: '难度不能为空',
                        trigger: 'change'
                    }
                ],
                public: [
                    {
                        required: true,
                        message: '可见范围不能为空',
                        trigger: 'change'
                    }
                ],
              deviceBaseType: [
                  {
                    required: true,
                    message: '实物设备类型不能为空',
                    trigger: 'change'
                  }
                ],

              
                // envtempid: [
                //     { required: true, validator: validateTemId, trigger: 'change' }
                // ],
                // guide: [
                //     { required: true, message: 'The guide cannot be empty', trigger: 'change' }
                // ],
                expType: [
                    {
                        required: true,
                        type: 'number',
                        message: '类型不能为空',
                        trigger: 'blur'
                    }
                ],
                selfType: [
                    {
                        required: true,
                        type: 'number',
                        message: '不能为空',
                        trigger: 'blur'
                    }
                ],
                // customType:[{
                // 	required:true,
                // 	type:'number',
                // 	message:'指导书类型不能为空',
                // 	trigger:'change'
                // }],
                desc: [
                    {
                        max: 200,
                        message: '描述不能超过200个字符',
                        trigger: 'change'
                    }
                ]
            },
            creatSceneLoading: false,
            useExpguideId: '',
            useTemplateId: '',
            useImagePath: '',
            // 课件类型
            expClassify: [],
            expClassifyLevel1: [],
            expClassifyLevel2: [],
            // 工程模板
            addDeviceModel: false,
            templatePage: 1,
            templatePageSize: 14,
            templateTotal: 0,
            templateList: [],
            templateCol: [
                {
                    title:'序号',
                    type: 'index',
                    width: 60,
                    align: 'left'
                },
                {
                    title: '模板名称',
                    key: 'name',
                    align: 'left'
                },
                {
                    title: '可见范围',
                    key: 'visibility',
                    width: 100,
                    align: 'left',
                    render: (h, params) => {
                        return h(
                            'div',
                            {
                                style: {
                                    color: this.handlePublic(params.row.visibility).color
                                }
                            },
                            this.handlePublic(params.row.visibility).text
                        );
                    }
                },
                {
                    title: '描述',
                    key: 'description',
                    align: 'left',
                    tooltip:true
                },
                {
                    title: '设计者',
                    key: 'creatorName',
                    width: 170,
                    align: 'left',
                    tooltip:true
                },
                // {
                //     title: '创建时间',
                //     key: 'created',
                //     minWidth: 120,
                //     align: 'left'
                // },
                {
                    title: '操作',
                    key: 'action',
                    align: 'left',
                    width: 120,
                    render: (h, params) => {
                        let text = '';
                        if (params.row.tempUserFlag) {
                            text = '已用';
                        } else {
                            text = '使用';
                        }
                        let status = this.getResourceDisStatus(
                            params.row.visibility === 'person',
                            params.row.creator
                        );
                        //						(this.formValidate.public == 1 || !this.isOwn) && params.row.visibility == 'person'
                        return h(
                            'a',
                            {
                                style: {
                                    //								'display': 'flex',
                                    //								'justify-content': 'flex-start',
                                    //								'align-items': 'center',
                                    color: status
                                        ? '#515a6e'
                                        : '#1d69da',
                                    cursor: status ? 'not-allowed' : 'pointer'
                                }
                            },
                            [
                                h(
                                    'div',
                                    {
                                        on: {
                                            click: () => {
                                                if (status) {
                                                    //this.$Message.warning('单位的课件不允许选择个人资源');
                                                    return;
                                                }
                                                this.chooseTemp(params);
                                            }
                                        },
                                        style: {
                                            //									'margin-left': '15px',
                                        }
                                    },
                                    [
                                        // h('img', {
                                        //     attrs: {
                                        //         src: params.row.tempUserFlag
                                        //             ? require('../../../../assets/globalIcon/choosed.png')
                                        //             : require('../../../../assets/globalIcon/add.png')
                                        //     },
                                        //     style: {
                                        //         'margin-right': '5px',
                                        //         'vertical-align': 'middle',
                                        //         width: '16px',
                                        //         height: '16px',
                                        //         display: 'inline-block'
                                        //     }
                                        // }),
                                        h('span', {}, text)
                                    ]
                                )
                            ]
                        );
                    }
                }
            ],
            searchTemplateName: '',
            proTemLoading: false,
            searchTemNameInput: '',
            selectProTemModel: '',
            templateVisibility: '',
            setUserTableHei: '700',
            // 说明指导书
            guideModal: false,
            guideLoading: false,
            expGuideList: [],
            expGuidePage: 1,
            expGuidePageSize: 14,
            expGuideTotal: 0,
            expGuideListCol: [
                {
                    type: 'index',
                    width: 60,
                    align: 'left'
                },
                {
                    title: '名称',
                    key: 'guidbookname',
                    align: 'left',
                    tooltip: true
                },
                {
                    title: '可见范围',
                    key: 'ispublic',
                    align: 'left',
                    render: (h, params) => {
                        return h(
                            'div',
                            {
                                style: {
                                    color: this.handlePublic(params.row.ispublic,true).color
                                }
                            },
                            this.handlePublic(params.row.ispublic).text
                        );
                    }
                },
                {
                    title: '是否为md格式',
                    key: 'templateid',
                    render: (h, params) => {
                        return h(
                            'div',
                            {
                                style: {
                                    color:
                                        params.row.templateid == 'markdown'
                                            ? '#28c09e'
                                            : '#db4747'
                                }
                            },
                            params.row.templateid == 'markdown' ? '是' : '否'
                        );
                    }
                },
                {
                    title: '设计者',
                    key: 'createuser',
                    align: 'left',
                    tooltip: true
                },
                {
                    type: 'showTime',
                    title: '最近一次更新时间',
                    key: 'updatetime',
                    align: 'left',
                    sortable: true,
                    tooltip: true
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'left',
                    render: (h, params) => {
                        let text = '';
                        if (params.row.guideUserFlag) {
                            text = '已用';
                        } else {
                            text = '使用';
                        }
                        let disUse =
                            this.getResourceDisStatus(
                                params.row.ispublic === 0,
                                params.row.designer
                            ) ||
                            !params.row.existSection ||
                            (params.row.expUsed &&
                                _this.formValidate.guideId !== params.row.guidbookid);
                        let item = params.row;
                        let disGuideModifyIsClick =
                            item.ispublic === '2' ||
                            item.ispublic === 2 ||
                            (item.designer !== this.USER_ID && !this.isRootDesinger);

                        //						(this.formValidate.public == 1 || !this.isOwn) && (params.row.ispublic === 0 || params.row.ispublic === '0')

                        return h('div', {}, [
                            h(
                                'span',
                                {
                                    style: {
                                        //								'display': 'flex',
                                        //								'justify-content': 'flex-start',
                                        //								'align-items': 'center',
                                        color: disUse
                                            ? '#515a6e'
                                            : '#1d69da',
                                        cursor: disUse ? 'not-allowed' : 'pointer'
                                    },
                                    on: {
                                        click: () => {
                                            if (disUse) {
                                                //this.$Message.warning('单位的课件不允许选择个人资源');
                                                return;
                                            }
                                            this.chooseGuide(params);
                                        }
                                    }
                                },
                                text
                            ),
                            h('Divider', {
                                props: {
                                    type: 'vertical'
                                },
                                style: {
                                    background: 'hsla(0,0%,100%,.12)'
                                }
                            }),
                            h(
                                'span',
                                {
                                    style: {
                                        color: !disGuideModifyIsClick
                                            ? '#1d69da'
                                            : '#515a6e',
                                        cursor: disGuideModifyIsClick ? 'not-allowed' : 'pointer'
                                    },
                                    on: {
                                        click: () => {
                                            if (disGuideModifyIsClick) {
                                                return;
                                            }
                                            this.editGuideModal.show = true;
                                            this.editGuideModal.type = 'update';
                                            this.editGuideModal.data = params.row;
                                        }
                                    }
                                },
                                '编辑'
                            )
                        ]);
                    }
                }
            ],
            searchGuideInput: '',
            shareStatus: 'all',
            // 图片
            imgModal: false,
            videoPage: 1,
            videoPageSize: 14,
            videoList: [],
            videoTotal: 0,
            videoCol: [
                {
                    title: '名称',
                    key: 'originName',
                    align: 'left'
                    // render:(h,params)=>{
                    //     let fileName = params.row.originName
                    //     fileName = fileName.split('.')[0]
                    //     return h('div',fileName)
                    // }
                },
                {
                    title: '缩略图',
                    key: 'path',
                    align: 'left',
                    render: (h, params) => {
                        return h('img', {
                            attrs: {
                                src: this.handleImage(params.row.path)
                            },
                            style: {
                                display: 'inline-block',
                                maxHeight: '40px',
                                width: 'auto',
                                verticalAlign: 'middle'
                            }
                        });
                    }
                },
                // {
                //     title: 'ID',
                //     key: 'id',
                //     align: 'left'
                // },
                
                //				{
                //					title: '类型',
                //					key: 'bucket',
                //					align: 'left',
                //					width: 80,
                //				},
                {
                    title: '可见范围',
                    key: 'visibility',
                    width: 100,
                    align: 'left',
                    render: (h, params) => {
                        return h(
                            'div',
                            {
                                style: {
                                    color: this.handlePublic(params.row.visibility).color
                                }
                            },
                            this.handlePublic(params.row.visibility).text
                        );
                    }
                },
                {
                    title: '内容',
                    key: 'check',
                    align: 'left',
                    width: 100,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'a',
                                {
                                    on: {
                                        click: () => {
                                            this.checkInfo(params);
                                        }
                                    }
                                },
                                '查看'
                            )
                        ]);
                    }
                },
                {
                    title: '设计者',
                    key: 'creatorName',
                    align: 'left'
                },
                // {
                //     title: '创建时间',
                //     key: 'created',
                //     align: 'left',
                //     minWidth: 120
                // },
                {
                    title: '操作',
                    key: 'action',
                    width: 100,
                    align: 'left',
                    render: (h, params) => {
                        let text = '';
                        if (params.row.imgUseFlag) {
                            text = '已用';
                        } else {
                            text = '使用';
                        }
                        let status = this.getResourceDisStatus(
                            params.row.visibility === 'person',
                            params.row.creator
                        );
                        //						(this.formValidate.public == 1 || !this.isOwn) && params.row.visibility == 'person'
                        return h(
                            'a',
                            {
                                style: {
                                    color: status
                                        ? '#515a6e'
                                        : '#1d69da',
                                    cursor: status ? 'not-allowed' : 'pointer'
                                },
                                on: {
                                    click: () => {
                                        if (status) {
                                            //this.$Message.warning('单位的课件不允许选择个人资源');
                                            return;
                                        }
                                        this.chooseImg(params);
                                    }
                                }
                            },
                            text
                        );
                    }
                }
            ],
            fileListLoading: false,
            searchFileName: '',
            searchFilePublic: '',
            //课件视频/课件
            expVideo: '',
            expDoc: '',
            imgDrawerTitle: '',
            imgDrawerSearchPlaceholder: '',
            currentStep: 1,
            questionList: [],
            questionStepFinishStatus: false,
            // 标签
            addExpModal:false,
            expClassifyTag: [],
            addLabels: '',
            addLabelsModal: false,
            addLabelsArr: [],
            mergeLabels: [],
            expClassifyName: []
        };
    },
    watch: {
        'formValidate.labels': {
            handler (val) {
                this.mergeLabels = [...new Set(this.formValidate.labels.concat(this.addLabelsArr))]
            },
            deep: true
        },
        addLabelsArr: {
            handler (val) {
                this.mergeLabels = [...new Set(this.formValidate.labels.concat(this.addLabelsArr))]
            },
            deep: true,
            immediate: true,
        },
        mergeLabels: {
            handler (val) {

            }, deep: true
        }
    },
    computed: {
        ...mapGetters(['breadList']),



      
        isOwn: function() {
            //是否是自己的（编辑别人的课件不允许选择个人资源）
            return this.USER_ID == this.formValidate.createUserId || this.isCreate;
        },
        pageTitle () {
            //当前菜单显示名
            return this.$route.meta.title;
        },
        pageLittleTitle () {
          //当前菜单显示名
          let pageTitle = this.breadList[0].name||''
          let name = pageTitle.substring(2,4)
          return name;
        },
        drawerFolderImage () {
            return this.closeIcon;
        },
        showNextBtn() {
            return this.currentStep < this.stepList.filter((step) => step.show).length;
        },
        stepList() {
            return [
                {
                    title: '基础信息',
                    show: true,
                    name: 'baseInfo',
                    finish: this.ecid ? true : false
                },
                {
                    title: '课件环境',
                    name: 'environ',
                    show: this.formValidate.expType === 0,
                    finish: this.environStepFinishStatus
                },
                {
                    title: '随堂练习',
                    name: 'question',
                    show: true,
                    finish: this.questionStepFinishStatus
                }
            ];
        }
    },
    created() {
        // 获取用户id
        let November = sessionStorage.getItem('November');
        November = JSON.parse(encryption.SelfUseDecrypt(November));
        this.USER_ID = November.userId;
        this.userName = November.userName;
        const typeMap = {
            0: '实操',
            2: '课件',
            1: '视频'
        };
        this.typeName = typeMap[this.$route.query.type];
        this.formValidate.expType = this.$route.query.type || 0;
        let curExp = sessionStorage.getItem('curExp');
        if (curExp) {
            sessionStorage.removeItem('curExp');
            let exp = JSON.parse(curExp);
            this.$router.push({
                name: 'creatExper',
                query: {
                    ecid: exp.ecid,
                    action: 'modify',
                    type: exp.type
                }
            });
        }
    },
    mounted () {
        // this.getDeviceType()
        this.getSelLabelType() 
        this.classification().then(() => {
            let breadList = this.breadList
            // 是创建还是编辑
            if (this.$route.query.action === 'create') {
                this.isCreate = true;
                this.titleText = `创建`+(breadList && breadList.length && breadList[0].name);
                this.showImgItem = true;
                this.formValidate.expType = this.$route.query.type||0;
            } else if (this.$route.query.action === 'modify') {
                this.isCreate = false;
                this.titleText = `修改`+(breadList && breadList.length && breadList[0].name);
                this.showImgItem = true;
                this.ecid = this.$route.query.ecid;
                this.getExperimentQuestion();
                this.getRepTemplateList();
                // 获取课件详情
                this.getExpInfo();
            }
            this.$store.commit('addBreadItem', { name: this.titleText });
        });
        // this.setStyle();
        // window.onresize = () => {
        //     this.setStyle();
        // };
    },
    beforeRouteLeave(to, from, next) {
        sessionStorage.removeItem('curExp');
        if (to.path === '/experiment') {
            //to.query.page = this.$route.query.page
            next();
        } else {
            //跳转至非课件页面，清空存储的查询条件
            sessionStorage.removeItem('queryObj');
            next();
        }
    },
    methods: {
    getDeviceType(){
      getDeviceType().then(res => {
        if (res.code == 1 && res.data) {// dictCode: 'VC', dictCnCode:
          let dtype = res.data.items||[]
    
          this.deviceTypes = dtype
        } else {
          console.error('获取实物设备类型失败，请刷新重试')
        }
      }).catch(error => {
        this.$Message.error({
          content: error,
          duration: 3,
        })
      })
    },
        // 
		selectExp () {
			this.addExpModal= true
		},
		submitLabelsSave(){},
		cancelLabelsSave(){},
		submitLabels () {
			// let arr2 = new Set(this.addLabelsArr) // 去重
			if (this.addLabels == '') { 
				this.addLabels = ''
				return
			}
				// 这里是可以多加标签和去除重复
			if (this.expClassifyName.includes(this.addLabels) || this.mergeLabels.includes(this.addLabels) || this.addLabelsArr.includes(this.addLabels)) {
				this.$Message.warning({
					content: `输入值${this.addLabels}重复数据，请重新输入！`,
					duration: 3
				})
				// this.addLabels = ''
			} else {
				this.addLabelsArr.push(this.addLabels)
				this.addLabels = ''
				this.addLabelsModal = false
			}
		},
		cancelLabels () {
			this.addLabels = ''
			this.addLabelsModal = false
		},
        handleCloseTag (item) { // 合拼数组问题，要对应处理对应的数组
            // let index = this.mergeLabels.indexOf(item)
            let addLabelsIndex = this.addLabelsArr.indexOf(item)
            let formIndex = this.formValidate.labels.indexOf(item)
            if (formIndex > -1) {
                this.formValidate.labels.splice(formIndex, 1)
            }
            if (addLabelsIndex > -1) {
                this.addLabelsArr.splice(addLabelsIndex, 1)
            }
            // if (index > -1) {
            // 	this.mergeLabels.splice(index, 1)
            // }
        },
        // 获取标签
        getSelLabelType () {
            getSelLabelType().then(res => {
                if (res.code == 1) {
                    this.expClassifyTag = res.data[0].dictEntryList
                    if (this.expClassifyTag.length > 0) {
                        this.expClassifyName = this.expClassifyTag.map(item => {
                            if (item) {
                                return item.dictname
                            }
                        })
                    }
                } else {
                    this.$Message.error('获取标签失败，请刷新重试')
                }
            }).catch(error => {
                this.$Message.error({
                    content: error,
                    duration: 3,
                })
            })
        },

        gotoStep(step) {
            console.log(' ~ step:', step)
            if (this.currentStep === 1 && step != 1) {
                this.submitBtn('formValidate', step);
            } else {
                this.currentStep = step;
                if (step === 1) {
                    let params = {
                        eid: this.ecid
                    };
                    experimentDetail(params).then((data) => {
                        if (data.code === 1) {
                            let getData = data.data;
                            this.useTemplateId = getData.envTempId;
                            if (getData.labels) {
                                let result = this.getLabelsSet(this.expClassifyTag, getData.labels.split(';'))
                                this.formValidate.labels = result.select
                                // this.addLabelsArr = result.input // 取消下拉框没有数据时，也不回显给创建输入框
                            }
                            // 查询工程模板
                            this.querytempByID(this.useTemplateId);
                            this.getExpVideoOrDocList()
                        } else {
                        }
                    });
                }
            }
        },
        switchStep(type) {
            if (type === 'next') {
                this.gotoStep(this.currentStep + 1);
            } else {
                this.gotoStep(this.currentStep - 1);
            }
        },
        returnList() {
            this.$router.go(-1);
        },
        handChangeSelectType(val) {
            this.edit.curSelectType = val;
        },
        getExperimentQuestion() {
            let params = {
                pageIndex: 1,
                pageSize: 1,
                ecid: this.ecid
            };
            queryExpQuestion(params)
                .then((data) => {
                    if (data.code == 1) {
                        this.questionList = data.data.items;
                        this.questionStepFinishStatus = this.questionList.length > 0;
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 设置高度
        setStyle() {
            window.fullHeight = document.documentElement.clientHeight;
            window.fullWidth = document.documentElement.clientWidth;
            this.fullHeight = window.fullHeight;
            this.fullWidth = window.fullWidth;
            this.contentHei = this.fullHeight - 60 - 21 + 'px'; // 80是头部高度  是上下padding
            this.setUserTableHei = this.fullHeight - 212;
            this.templatePageSize = Math.floor(this.setUserTableHei / 50) - 1;
            this.expGuidePageSize = Math.floor(this.setUserTableHei / 50) - 1;
            this.videoPageSize = Math.floor(this.setUserTableHei / 50) - 1;
        },
        // 返回课件列表
        returnImage() {
            const name =
                this.typeName == '课件'
                    ? 'coursewareExp'
                    : this.typeName == '视频'
                    ? 'videoLearn'
                    : 'experiment';
            this.$router.push({
                name: name,
                query: {
                    page: this.$route.query.page
                }
            });
        },
        changeGuideType(val) {
            if (val) {
                //文件File
                if (this.preGuideIdFile) {
                    this.useExpguideId = this.preGuideIdFile;
                    this.formValidate.guide = this.preGuideNameFile;
                } else {
                    this.useExpguideId = '';
                    this.formValidate.guide = '';
                }
            } else {
                if (this.preGuideIdData) {
                    this.useExpguideId = this.preGuideIdData;
                    this.formValidate.guide = this.preGuideNameData;
                } else {
                    this.useExpguideId = '';
                    this.formValidate.guide = '';
                }
            }
        },
        // 获取课件详情 回显数据
        getExpInfo() {
            let params = {
                eid: this.ecid
            };
            experimentDetail(params)
                .then((data) => {
                    if (data.code === 1) {
                        let getData = data.data;
                        this.receiveData = getData;
                        this.formValidate.name = this.escape2Html(getData.ecname);
                        this.formValidate.relaDevice = getData.deviceBaseType?1:0;
                        
                        if(getData.deviceBaseType){
                          this.handChangeSelectType('image')
                          this.formValidate.deviceBaseType = getData.deviceBaseType.split(',')
                        }
                        
                        // this.$store.commit('addBreadItem', { name: getData.ecname });
                        this.formValidate.difficulty = getData.difficulty;
                        this.formValidate.desc = this.escape2Html(getData.description);
                        this.formValidate.hours = getData.hours;
                        this.formValidate.type = getData.typeCode;
                        this.formValidate.selfType = getData.selfType;
                        let direction = this.getDirection(getData.typeCode);
                        this.expClassifyLevel2 = this.expClassify.filter(
                            (dict) => dict.parentid == direction
                        );
                        this.formValidate.direction = direction;
                        this.formValidate.expType = getData.expType;
                        this.formValidate.customType = getData.customType
                            ? parseInt(getData.customType)
                            : 0;
                        this.formValidate.public = getData.isPublic;
                        this.formValidate.topology = getData.topology;
                        this.formValidate.createUserId = getData.createUserId;
                        this.useImagePath = getData.topology;
                        this.useExpguideId = getData.guide;
                        if (this.formValidate.customType) {
                            this.preGuideIdFile = this.useExpguideId;
                            this.preGuideNameFile = this.formValidate.guide;
                        } else {
                            this.preGuideIdData = this.useExpguideId;
                            this.preGuideNameData = this.formValidate.guide;
                        }
                        if (getData.labels) {
                            let result = this.getLabelsSet(this.expClassifyTag, getData.labels.split(';'))
                            this.formValidate.labels = result.select
                            // this.addLabelsArr = result.input // 取消下拉框没有数据时，也不回显给创建输入框
                        }
                        this.useTemplateId = getData.envTempId;
                        if (getData.expType == 0) {
                            // 查询指导书
                            if (!this.formValidate.customType) {
                                //0 不变
                                this.queryGuideByID(this.useExpguideId);
                            } else {
                                this.formValidate.guide = getData.reportTemplate;
                                this.preGuideNameFile = this.formValidate.guide;
                            }
                            // 查询工程模板
                            this.querytempByID(this.useTemplateId);
                            //查询课件视频和课件信息
                            this.getExpVideoOrDocList();
                        } else if (getData.expType == 1) {
                            //查询课件视频和课件信息
                            this.getExpVideoOrDocList();
                            // 查询指导书
                            if (this.useExpguideId) {
                                // 查询指导书
                                if (!this.formValidate.customType) {
                                    //0 不变
                                    this.queryGuideByID(this.useExpguideId);
                                } else {
                                    this.formValidate.guide = getData.reportTemplate;
                                }
                            }
                        } else if (getData.expType == 2) {
                            //查询课件课件信息
                            this.getExpVideoOrDocList();
                        }
                    } else {
                        this.$Message.error({
                            content: data.message,
                            duration: 3
                        });
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        getLabelsSet (data1, data2) {
            let result = {
                select: [],
                input: []
            }
            data2.forEach(item2 => {
                data1.forEach(item => {
                    if (item2 !== item.dictname) {
                        result.input.push(item2)
                    } else {
                        result.select.push(item2)
                    }
                })
            })
            result.input = [...new Set(result.input)]
            result.select = [...new Set(result.select)]
            return result;
        },
        getDirection(type) {
            let types = this.expClassify.filter((dict) => dict.dictid == type);
            if (types.length > 0) {
                let parentTypes = this.expClassify.filter(
                    (dict) => dict.dictid == types[0].parentid
                );
                return parentTypes.length > 0 ? parentTypes[0].dictid : '';
            } else {
                return '';
            }
        },
        getResourceDisStatus(isPrivate, creator) {
            let isNotOwn = !(this.USER_ID == this.formValidate.createUserId || this.isCreate);
            let isNotCommonCreator = this.formValidate.createUserId !== creator && !this.isCreate;
            return (this.formValidate.public == 1 || (isNotOwn && isNotCommonCreator)) && isPrivate;
        },
        // 提交按钮
        submitBtn(name, step) {
            if (this.isCreate) {
                this.submitExpSceneBtn(name, step);
            } else {
                this.modifySubmit(name, step);
            }
            if (this.addLabelsArr.length > 0) {
                this.dictEntrysSave()
            }
        },
        // 保存标签
        dictEntrysSave () {
            if (this.addLabelsArr.length == 0) return;
            if (this.addLabelsArr.length == 1) { // 单个数据保存
                let name = this.addLabelsArr[0]
                let res = dictEntrysSave(name)
                console.log('dictEntrysSave ~ res', res)
            } else {
                let result = dictEntrysSaveBatch(this.addLabelsArr)
                console.log('dictEntrysSave ~ result', result)
            }
        },
        // 创建提交
        submitExpSceneBtn(name, step) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let formData = {};
                    if(this.formValidate.relaDevice===1 && this.formValidate.deviceBaseType){ // 关联实物设备的话
                      formData.deviceBaseType = this.formValidate.deviceBaseType+'';
                    }else {
                      formData.deviceBaseType=''
                    }
                    
                    formData.ecname = this.formValidate.name;
                    formData.difficulty = this.formValidate.difficulty;
                    formData.description = this.formValidate.desc;
                    formData.hours = this.formValidate.hours;
                    formData.guide = this.useExpguideId;
                    formData.typeCode = this.formValidate.type;
                    formData.isPublic = this.formValidate.public;
                    // formData.labels = 'null';
						// formData.labels = this.formValidate.labels.join(';');
                    if (this.mergeLabels.length > 0 || this.formValidate.labels.length > 0) {
                        formData.labels = this.mergeLabels.join(';');
                    } else {
                        formData.labels = ''
                    }
                    formData.vmCount = '0';
                    formData.envTempId = this.useTemplateId;
                    formData.srcId = '';
                    formData.topology = this.useImagePath;
                    formData.expType = this.formValidate.expType;
                    formData.customType = this.formValidate.customType;
                    formData.selfType = this.formValidate.selfType;
                    // 分界线
                    formData.reportTemplate = '';
                    formData.usedTimes = '0';
                    formData.createUserId = this.USER_ID;
                    formData.testingResult = '0';
                    formData.testingUser = '';
                    formData.isTested = '1';
                    formData.designer = this.userName;
                    formData.filePath = '';
                    formData.testingtime = '';
                    formData.userName = this.userName;
                    formData.testStatus = this.formValidate.expType === 0 ? 0 : 1;
                    if (formData.customType) {
                        formData.reportTemplate = this.formValidate.guide;
                    }
                    if (formData.envTempId === '' && formData.expType == 0) {
                        this.$Message.error({
                            content: '请选择一个工程模板',
                            duration: 3
                        });
                        return false;
                    } else if (formData.guide === '' && formData.expType == 0) { // 实操
                        this.$Message.error({
                            content: '请选择一个指导书',
                            duration: 3
                        });
                        return false;
                    } else if (this.expVideo == '' && this.expDoc == '' && formData.guide == '' && formData.expType == 1) { // 视频/理论
                        this.$Message.error({
                            content: '视频、课件或指导书中至少选择一种',
                            duration: 3
                        });
                        return false;
                    } else if (this.expDoc == '' && formData.expType == 2) {
                        this.$Message.error({
                            content: '请选择一个课件',
                            duration: 3
                        });
                        return false;
                    }
                    this.creatSceneLoading = true;
                    submitExper(formData)
                        .then((data) => {
                            if (data.code == 1) {
                                this.ecid = data.data.ecId;
                                this.isCreate = false;
                                sessionStorage.setItem(
                                    'curExp',
                                    JSON.stringify({
                                        ecid: this.ecid,
                                        type: this.formValidate.expType
                                    })
                                );
                                if (!this.expDoc && !this.expVideo) {
                                    this.$Message.success({
                                        content: '创建成功！',
                                        duration: 3
                                    });
                                    this.currentStep = step;
                                    // this.handleReset('formValidate');
                                    // setTimeout(() => {
                                    //     this.returnImage();
                                    // });
                                } else if (this.expDoc && this.expVideo) {
                                    Promise.all([
                                        this.saveExperOrDocInfo('EduPdf'),
                                        this.saveExperOrDocInfo('EduVideo')
                                    ]).then((data) => {
                                        this.$Message.success({
                                            content: '创建成功！',
                                            duration: 3
                                        });
                                        this.currentStep = step;
                                        // this.handleReset('formValidate');
                                        // setTimeout(() => {
                                        //     this.returnImage();
                                        // });
                                    });
                                } else if (this.expDoc) {
                                    this.saveExperOrDocInfo('EduPdf').then((data) => {
                                        if (data) {
                                            this.$Message.success({
                                                content: '创建成功！',
                                                duration: 3
                                            });
                                            this.currentStep = step;
                                            // this.handleReset('formValidate');
                                            // setTimeout(() => {
                                            //     this.returnImage();
                                            // });
                                        }
                                    });
                                } else if (this.expVideo) {
                                    this.saveExperOrDocInfo('EduVideo').then((data) => {
                                        if (data) {
                                            this.$Message.success({
                                                content: '创建成功！',
                                                duration: 3
                                            });
                                            this.currentStep = step;
                                            // this.handleReset('formValidate');
                                            // setTimeout(() => {
                                            //     this.returnImage();
                                            // });
                                        }
                                    });
                                }
                                
                            } else {
                                this.$Message.error({
                                    content: data.message,
                                    duration: 3
                                });
                            }
                            this.addLabelsArr = []
                            this.getSelLabelType()
                            this.creatSceneLoading = false;
                        })
                        .catch((err) => {
                            this.creatSceneLoading = false;
                            console.log(err);
                        });
                } else {
                    this.$Message.error('请完善信息!');
                }
            });
        },
        // 编辑提交
        modifySubmit(name, step) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.receiveData.ecid = this.ecid;
                    this.receiveData.ecname = this.formValidate.name;

                  if(this.formValidate.relaDevice===1 && this.formValidate.deviceBaseType){ // 关联实物设备的话
                    this.receiveData.deviceBaseType = this.formValidate.deviceBaseType+'';
                  }else {
                    this.receiveData.deviceBaseType=''
                  }
                  
                    
                    this.receiveData.typeCode = this.formValidate.type;
                    this.receiveData.hours = parseInt(this.formValidate.hours);
                    this.receiveData.difficulty = this.formValidate.difficulty;
                    this.receiveData.isPublic = parseInt(this.formValidate.public);
                    this.receiveData.description = this.formValidate.desc;
                    this.receiveData.guide = this.useExpguideId;
                    this.receiveData.envTempId = this.useTemplateId || '';
                    this.receiveData.topology = this.useImagePath;
                    this.receiveData.expType = this.formValidate.expType;
                    this.receiveData.customType = this.formValidate.customType;
                    this.receiveData.testStatus = this.formValidate.testStatus;
                    this.receiveData.selfType = this.formValidate.selfType;
                    if (this.mergeLabels.length > 0 || this.formValidate.labels.length > 0) {
                        this.receiveData.labels = this.mergeLabels.join(';');
                    } else {
                        this.receiveData.labels = ''
                    }
                    if (this.receiveData.customType) {
                        this.receiveData.reportTemplate = this.formValidate.guide;
                    }
                    if (this.receiveData.envTempId === '' && this.receiveData.expType == 0) {
                        this.$Message.error({
                            content: '请选择一个工程模板',
                            duration: 3
                        });
                        return false;
                    } else if (this.receiveData.guide === '' && this.receiveData.expType == 0) {
                        this.$Message.error({
                            content: '请选择一个指导书',
                            duration: 3
                        });
                        return false;
                    } else if (this.expVideo == '' && this.expDoc == '' && this.receiveData.guide == '' && this.receiveData.expType == 1) {
                        this.$Message.error({
                            content: '视频、课件或指导书中至少选择一种',
                            duration: 3
                        });
                        return false;
                    } else if (this.expDoc == '' && this.receiveData.expType == 2) {
                        this.$Message.error({
                            content: '请选择一个课件',
                            duration: 3
                        });
                        return false;
                    }
                    this.creatSceneLoading = true;
                    modifyExper(this.receiveData.ecid, this.receiveData)
                        .then((data) => {
                            if (data.code == 1) {
                                if (
                                    (!this.expDoc && this.curSaveExpDoc) ||
                                    (!this.expVideo && this.curSaveExpVideo)
                                ) {
                                    //存在删除的情况，先清空
                                    this.clearExpVideo().then((data) => {
                                        this.curSaveExpVideo = '';
                                        this.curSaveExpDoc = '';
                                        if (data) {
                                            if (!this.expDoc && !this.expVideo) {
                                                this.$Message.success({
                                                    content: '编辑成功！',
                                                    duration: 3
                                                });
                                                this.currentStep = step;
                                                // this.handleReset('formValidate');
                                                // setTimeout(() => {
                                                //     this.returnImage();
                                                // });
                                            } else {
                                                if (this.expVideo) {
                                                    this.saveExperOrDocInfo('EduVideo').then(
                                                        (data) => {
                                                            this.$Message.success({
                                                                content: '编辑成功！',
                                                                duration: 3
                                                            });
                                                            this.currentStep = step;
                                                            // this.handleReset('formValidate');
                                                            // setTimeout(() => {
                                                            //     this.returnImage();
                                                            // }, 1000);
                                                        }
                                                    );
                                                }
                                                if (this.expDoc) {
                                                    this.saveExperOrDocInfo('EduPdf').then(
                                                        (data) => {
                                                            this.$Message.success({
                                                                content: '编辑成功！',
                                                                duration: 3
                                                            });
                                                            this.currentStep = step;
                                                            // this.handleReset('formValidate');
                                                            // setTimeout(() => {
                                                            //     this.returnImage();
                                                            // }, 1000);
                                                        }
                                                    );
                                                }
                                            }
                                        }
                                    });
                                } else if (this.expDoc || this.expVideo) {
                                    let proArr = [];
                                    if (this.expDoc && this.expVideo) {
                                        proArr = [
                                            this.saveExperOrDocInfo('EduPdf'),
                                            this.saveExperOrDocInfo('EduVideo')
                                        ];
                                    } else if (this.expDoc) {
                                        proArr = [this.saveExperOrDocInfo('EduPdf')];
                                    } else if (this.expVideo) {
                                        proArr = [this.saveExperOrDocInfo('EduVideo')];
                                    }
                                    Promise.all([proArr]).then((data) => {
                                        this.$Message.success({
                                            content: '编辑成功！',
                                            duration: 3
                                        });
                                        this.currentStep = step;
                                        // this.handleReset('formValidate');
                                        // setTimeout(() => {
                                        //     this.returnImage();
                                        // }, 1000);
                                    });
                                } else {
                                    this.$Message.success({
                                        content: '编辑成功！',
                                        duration: 3
                                    });
                                    this.currentStep = step;
                                    // this.handleReset('formValidate');
                                    // setTimeout(() => {
                                    //     this.returnImage();
                                    // }, 1000);
                                }
                               
                            } else {
                                this.$Message.error({
                                    content: data.message,
                                    duration: 3
                                });
                            }
                            this.addLabelsArr = []
                            this.getSelLabelType()
                            this.creatSceneLoading = false;
                        })
                        .catch((err) => {
                            this.creatSceneLoading = false;
                            console.log(err);
                        });
                } else {
                    this.$Message.error('请完善信息!');
                }
            });
        },
        // 重置
        handleReset(name) {
            this.useTemplateId = '';
            this.useExpguideId = '';
            this.useImagePath = '';
            this.guideFilePath = '';
            this.$refs[name].resetFields();
            this.expDoc = '';
            this.expVideo = '';
            this.useTempVisibility = '';
            this.useGuideVisibility = '';
            this.useImageVisibility = '';
            this.useExpDocVisibility = '';
            this.useExpVideoVisibility = '';
            this.useExpGuideVisibility = '';
        },
        // 获取场景类型
        classification() {
            return new Promise((resolve, reject) => {
                experType()
                    .then((data) => {
                        if (data.code == 1) {
                            let attribute = data.attribute;
                            this.expClassify = attribute.attribute[0].dictEntryList;
                            this.expClassifyLevel1 = attribute.attribute[0].dictEntryList.filter(
                                (dict) => !dict.parentid
                            );
                            this.expClassifyLevel2 = attribute.attribute[0].dictEntryList.filter(
                                (dict) => dict.parentid
                            );
                            resolve(data.attribute);
                        } else {
                            resolve();
                        }
                    })
                    .catch((err) => {
                        resolve();
                        console.log(err);
                    });
            });
        },
        // 选择工程模板
        toPlateTabs(type) {
            this.addDeviceModel = true;
            this.templateList = [];
            let params = {
                pageIndex: this.templatePage,
                pageSize: this.templatePageSize
            };
            let data = {
                name: this.searchTemplateName,
                visibility: this.templateVisibility,
                type: 'project',
                // markType: this.edit.curTemplateType // 这个系统没有普通模板和基础模板的区分了，直接查工程模板
            };
            this.proTemLoading = true;
            getTemplateData(data, params)
                .then((res) => {
                    let data = res.data;
                    if (data.code === 1) {
                        let pateInfo = data.data;
                        this.templateTotal = Number(pateInfo.total);
                        let items = pateInfo.items;
                        for (let i = 0; i < items.length; i++) {
                            items[i].tempUserFlag = false;
                            if (items[i].id === this.useTemplateId) {
                                items[i].tempUserFlag = true;
                            }
                        }
                        this.templateList = items;
                    } else {
                        this.templateList = [];
                        this.templateTotal = 0;
                    }
                    this.proTemLoading = false;
                })
                .catch((err) => {
                    this.proTemLoading = false;
                    console.log(err);
                });
        },
        temOnChange(val) {
            this.templatePage = val;
            this.toPlateTabs();
        },
        changeTemplate(val) {
            this.templatePage = 1;
            this.templateVisibility = val;
            this.toPlateTabs();
        },
        searchTemNameBtn(val) {
            this.templatePage = 1;
            this.searchTemplateName = this.searchTemNameInput;
            this.toPlateTabs();
        },
        refreshTem(type) {
            this.edit.curTemplateType = type;
            this.templatePage = 1;
            this.searchTemplateName = '';
            this.searchTemNameInput = '';
            this.templateVisibility = '';
            this.selectProTemModel = '';
            this.toPlateTabs();
        },
        closeDistribution() {
            this.addDeviceModel = false;
        },
        chooseTemp(params) {
            if (params.row.tempUserFlag) {
                this.$Message.info({
                    content: '已使用该模板！',
                    duration: 3
                });
            } else {
                let _index = params.row._index;
                for (let i = 0; i < this.templateList.length; i++) {
                    this.templateList[i].tempUserFlag = false;
                }
                this.$set(this.templateList[_index], 'tempUserFlag', true);
                this.formValidate.envtempid = params.row.name;
                this.useTemplateId = params.row.id;
                //存储模板可见范围
                this.useTempVisibility = params.row.visibility;
            }
        },

        getTemplateInfoImage(info) {
          // debugger
        
          this.formValidate.envtempid = info.name;
          this.formValidate.deviceBaseType = info.deviceBaseType.toString();
          if(info.deviceBaseType){
            this.formValidate.relaDevice = 1
          }
  
          this.useTemplateId = info.id;
          //存储模板可见范围
          this.useTempVisibility = 'person';
        },
        getTemplateInfo(info) {
            this.formValidate.deviceBaseType = "";
            this.formValidate.relaDevice = 0
            
            this.formValidate.envtempid = info.name;
            this.useTemplateId = info.id;
            //存储模板可见范围
            this.useTempVisibility = 'person';
        },
        querytempByID(id) {
            getTempInfpByID(id)
                .then((res) => {
                    if (res.data.code === 1) {
                        this.formValidate.envtempid = res.data.data.name;
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 清除选中的模板
        clearTemp() {
            this.formValidate.envtempid = '';
            this.useTemplateId = '';
        },
        searchGuideData() {
            if (this.formValidate.customType === 1) {
                //1文件
                this.getVideoList('docs');
            } else {
                this.showGuideBtn();
            }
        },
        //指导书文件类型
        showGuideBtnFile() {
            this.guideFileModal = true;
            let params = {
                page: this.expGuideFilePage,
                rows: this.expGuideFilePageSize,
                // isExpUsed: false, // 是否被课件使用 NULL=全部，true=被课件， false=未被使用
                order: 'desc',
                sortBy: 'createtime'
            };
            let data = {
                bucket: 'docs'
            };
            if (this.shareFileStatus != 'all') {
                data.visibility = this.shareFileStatus;
            }
            if ($.trim(this.searchGuideFileInput) != '') {
                data.originName = this.searchGuideFileInput;
            }
            this.guideFileLoading = true;
            getGuideFileData(params)
                .then((data) => {
                    if (data.code == 1) {
                        let attribute = data.attribute;
                        let items = attribute.dataList;
                        for (let i = 0; i < items.length; i++) {
                            items[i].guideUserFlag = false;
                            if (items[i].guidbookid === this.useExpguideId) {
                                items[i].guideUserFlag = true;
                            }
                        }
                        this.expGuideList = items;
                        this.expGuideTotal = attribute.totalCount;
                    }
                    this.guideLoading = false;
                })
                .catch((err) => {
                    console.log(err);
                    this.guideLoading = false;
                });
        },
        // 指导书
        showGuideBtn() {
            this.guideModal = true;
            let params = {
                page: this.expGuidePage,
                rows: this.expGuidePageSize,
                order: 'desc',
                sortBy: 'createtime',
                ecId: this.ecid || '',
                isExpUsed: false, //未被使用的指导书  是否被课件使用 NULL=全部，true=被课件， false=未被使用
                // isIncludeUnusable:true, // 没有段落过滤
            };
            if (this.shareStatus != 'all') {
                params.ispublic = this.shareStatus;
            }
            if ($.trim(this.searchGuideInput) != '') {
                params.guidbookname = this.searchGuideInput;
            }
            if(!params.ecId){
                delete params.ecId;
            }
            this.guideLoading = true;
            getGuideData(params)
                .then((data) => {
                    if (data.code == 1) {
                        let attribute = data.attribute;
                        let items = attribute.dataList;
                        for (let i = 0; i < items.length; i++) {
                            items[i].guideUserFlag = false;
                            if (items[i].guidbookid === this.useExpguideId) {
                                items[i].guideUserFlag = true;
                            }
                        }
                        this.expGuideList = items;
                        this.expGuideTotal = attribute.totalCount;
                    }
                    this.guideLoading = false;
                })
                .catch((err) => {
                    console.log(err);
                    this.guideLoading = false;
                });
        },
        guideOnChange(val) {
            this.expGuidePage = val;
            this.showGuideBtn();
        },
        changeType(val) {
            this.expGuidePage = 1;
            this.shareStatus = val;
            this.showGuideBtn();
        },
        searchGuideBtn() {
            this.expGuidePage = 1;
            this.showGuideBtn();
        },
        refreshFile() {
            if (this.formValidate.customType) {
                //1文件
                this.refreshImg('docs');
            } else {
                this.expGuidePage = 1;
                this.searchGuideInput = '';
                this.shareStatus = 'all';
                this.showGuideBtn();
            }
        },
        closeGuideModalBtn() {
            this.guideModal = false;
        },
        chooseGuide(params) {
            if (params.row.guideUserFlag) {
                this.$Message.info({
                    content: '已使用该指导书！',
                    duration: 3
                });
            } else {
                let _index = params.row._index;
                for (let i = 0; i < this.expGuideList.length; i++) {
                    this.expGuideList[i].guideUserFlag = false;
                }
                this.$set(this.expGuideList[_index], 'guideUserFlag', true);
                this.formValidate.guide = params.row.guidbookname;
                this.useExpguideId = params.row.guidbookid;
                this.preGuideIdData = this.useExpguideId;
                this.preGuideNameData = this.formValidate.guide;
                //存储指导书可见范围
                this.useGuideVisibility = params.row.ispublic;
            }
        },
        queryGuideByID(id) {
            getGuideInfoByID_new(this.ecid, id)
                .then((data) => {
                    if (data.code === 1) {
                        let guideInfo = data.attribute.data;
                        this.useExpguidePublic = guideInfo.ispublic;
                        this.formValidate.guide = guideInfo.guidbookname;
                        this.preGuideNameData = guideInfo.guidbookname;
                        this.formValidate.guideId = guideInfo.guidbookid;
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 清除选中的指导书
        clearGuide() {
            this.formValidate.guide = '';
            this.useExpguideId = '';
            if (this.formValidate.customType) {
                if (this.preGuideIdFile) {
                    this.preGuideIdFile = '';
                    this.preGuideNameFile = '';
                }
            } else {
                if (this.preGuideIdData) {
                    this.preGuideIdData = '';
                    this.preGuideNameData = '';
                }
            }
        },
        getShowVideoCol() {
            if (this.selectType != 'images') {
                return this.videoCol.filter((col) => col.key != 'path');
            } else {
                return this.videoCol;
            }
        },
        // 选择图片
        getVideoList(type) {
            this.imgModal = true;
            this.selectType = type;
            if (type == 'images') {
                this.imgDrawerTitle = '封面图片';
                this.imgDrawerSearchPlaceholder = '图片名称';
                this.getVideoImage(type)
                return
                
            } else if (type == 'videos') {
                this.imgDrawerTitle = '视频';
                this.imgDrawerSearchPlaceholder = '视频名称';
            } else if (type == 'docs') {
                this.imgDrawerTitle = '指导书';
                this.imgDrawerSearchPlaceholder = '指导书名称';
            } else {
                this.imgDrawerTitle = '课件';
                this.imgDrawerSearchPlaceholder = '课件名称';
            }
            let params = {
                pageIndex: this.videoPage,
                pageSize: this.videoPageSize
            };
            let data = {
                bucket: type //images/courseware/videos/docs
            };
            if ($.trim(this.searchFileName) != '') {
                data.originName = $.trim(this.searchFileName);
            }
            if ($.trim(this.searchFilePublic) != '') {
                data.visibility = $.trim(this.searchFilePublic);
            }
            this.fileListLoading = true;
            getFilesData(params, data)
                .then((res) => {
                    if (res.data.code == 1) {
                        let attribute = res.data.data;
                        let items = attribute.list;
                        this.videoTotal = attribute.total;
                        for (let i = 0; i < items.length; i++) {
                            items[i].imgUseFlag = false;
                            if (
                                (items[i].path === this.useImagePath && type == 'images') ||
                                (items[i].path === this.expDoc.path && type == 'courseware') ||
                                (items[i].path === this.expVideo.path && type == 'videos') ||
                                (items[i].path === this.useExpguideId && type == 'docs')
                            ) {
                                items[i].imgUseFlag = true;
                            }
                        }
                        this.videoList = items;
                    }
                    this.fileListLoading = false;
                })
                .catch((err) => {
                    this.fileListLoading = false;
                });
        },
        getVideoImage(type) {
          let params = {
            pageIndex: this.videoPage,
            pageSize: this.videoPageSize,
            self:0
          };
          let data = {
            type:'Covertitle',
            self:0
          };
          if ($.trim(this.searchFileName) != '') {
            data.name = $.trim(this.searchFileName);
          }
          if ($.trim(this.searchFilePublic) != '') {
            data.visibility = $.trim(this.searchFilePublic);
          }
          this.fileListLoading = true;
          getIconData(data,params)
          .then((res) => {
            if (res.data.code == 1) {
              let attribute = res.data.data;
              let items = attribute.items||[];
              this.videoTotal = attribute.total;
  
              for (let i = 0; i < items.length; i++) {
                items[i].originName = items[i].name
                items[i].path = items[i].path.replace('/files/','')
                items[i].imgUseFlag = false;
                if (
                    (items[i].path === this.useImagePath && type == 'images') ||
                    (items[i].path === this.expDoc.path && type == 'courseware') ||
                    (items[i].path === this.expVideo.path && type == 'videos') ||
                    (items[i].path === this.useExpguideId && type == 'docs')
                ) {
                  items[i].imgUseFlag = true;
                }
              }
  
  
              this.videoList = items;
            }
            this.fileListLoading = false;
          })
          .catch((err) => {
            this.fileListLoading = false;
          });
        },
        videoOnChange(val) {
            this.videoPage = val;
            this.getVideoList(this.selectType);
        },
        searchFile(val) {
            this.videoPage = 1;
            this.getVideoList(this.selectType);
        },
        refreshImg(type) {
            this.videoPage = 1;
            this.searchFileName = '';
            this.searchFilePublic = '';
            const curType = type || this.selectType;
            this.getVideoList(curType);
        },
        closeImgModalBtn() {
            this.imgModal = false;
        },
        checkInfo(params) {
            let path = params.row.path;
            if (params.row.originName.endsWith('.md')) {
                let href = this.$router.resolve({
                    name: 'mdPreview',
                    query: {
                        path: path,
                        name: params.row.originName
                    }
                }).href;
                window.openTrain(href, '_blank');
            } else {
                window.openTrain(`/api/minio/filePreview?path=${path}`);
            }
        },
        chooseImg(params) {
            if (this.selectType == 'images') {
                if (params.row.imgUseFlag) {
                    this.$Message.info({
                        content: '已使用该图片！',
                        duration: 3
                    });
                } else {
                    let _index = params.row._index;
                    for (let i = 0; i < this.videoList.length; i++) {
                        this.videoList[i].imgUseFlag = false;
                    }
                    this.$set(this.videoList[_index], 'imgUseFlag', true);
                    this.formValidate.topology = params.row.originName;
                    this.useImagePath = params.row.path;
                    //存储图片可见范围
                    this.useImageVisibility = params.row.visibility;
                    this.$refs.imageUpload.hideTip();
                }
            } else if (this.selectType == 'courseware') {
                if (params.row.imgUseFlag) {
                    this.$Message.info({
                        content: '已使用该课件！',
                        duration: 3
                    });
                } else {
                    let _index = params.row._index;
                    for (let i = 0; i < this.videoList.length; i++) {
                        this.videoList[i].imgUseFlag = false;
                    }
                    this.$set(this.videoList[_index], 'imgUseFlag', true);
                    this.expDoc = params.row;
                    //存储课件可见范围
                    this.useExpDocVisibility = params.row.visibility;
                    this.$refs.coursewareUpload.hideTip();
                }
            } else if (this.selectType == 'videos') {
                if (params.row.imgUseFlag) {
                    this.$Message.info({
                        content: '已使用该视频！',
                        duration: 3
                    });
                } else {
                    let _index = params.row._index;
                    for (let i = 0; i < this.videoList.length; i++) {
                        this.videoList[i].imgUseFlag = false;
                    }
                    this.$set(this.videoList[_index], 'imgUseFlag', true);
                    this.expVideo = params.row;
                    this.expVideo.originName = this.expVideo.originName || this.expVideo.originalName
                    //存储视频可见范围
                    this.useExpVideoVisibility = params.row.visibility||"person";
                    this.$refs.videoUpload.hideTip();
                }
            } else if (this.selectType == 'docs') {
                //guideFilePath
                if (params.row.imgUseFlag) {
                    this.$Message.info({
                        content: '已使用该指导书文件！',
                        duration: 3
                    });
                } else {
                    let _index = params.row._index;
                    for (let i = 0; i < this.videoList.length; i++) {
                        this.videoList[i].imgUseFlag = false;
                    }
                    this.$set(this.videoList[_index], 'imgUseFlag', true);
                    this.formValidate.guide = params.row.originName;
                    this.useExpguideId = params.row.path;
                    this.preGuideIdFile = this.useExpguideId;
                    this.preGuideNameFile = this.formValidate.guide;
                    //存储指导书可见范围
                    this.useGuideVisibility = params.row.visibility;
                    this.$refs.guideUpload.hideTip();
                }
            }
        },
        getUrlAndSaveType(file, type){
          let iconDto = {
            type:'Covertitle',
            name:file.info.originalName,
            visibility:'person',// 创建课件的时候，图片都是个人的
            description:'封面图片',
            path:file.data,
          }
          for (let key in iconDto) {
            if (!iconDto[key]) {
              iconDto[key] = null
            }
          }
          // 上传成功后保存到我们的数据库里面，把类型也保存上去
          createIcon(iconDto)
          
          this.getUrl(file,type)
        },
      
        getUrl(file, type) {
            if (type === 'videos') {
                this.expVideo = {
                    id: file.info.id,
                    path: file.data,
                    originName: file.info.originalName,
                    duration: file.info.duration
                };
                //存储视频可见范围
                this.useExpVideoVisibility = 'person';
            } else if (type === 'guide') {
                //存储指导书可见范围
                this.useGuideVisibility = 'person';
                this.formValidate.guide = file.info.originalName;
                this.useExpguideId = file.data;
                this.preGuideIdFile = this.useExpguideId;
                this.preGuideNameFile = this.formValidate.guide;
                //存储指导书可见范围
                this.useGuideVisibility = 'person';
            } else if (type === 'images') {
                this.formValidate.topology = file.info.originalName;
                this.useImagePath = file.data;
                //存储图片可见范围
                this.useImageVisibility = 'person';
            } else if (type === 'courseware') {
                this.expDoc = {
                    id: file.info.id,
                    path: file.data,
                    originName: file.info.originalName
                };
                //存储课件可见范围
                this.useExpDocVisibility = 'person';
            }
        },
        getGuideInfo(guide) {
            if (!guide) {
                return;
            }
            this.formValidate.guide = guide.name;
            this.useExpguideId = guide.id;
            this.preGuideIdFile = this.useExpguideId;
            this.preGuideNameFile = this.formValidate.guide;
        },
        // 清空选择的图片
        clearImg() {
            this.formValidate.topology = '';
            this.useImagePath = '';
        },
        //清除选中的课件
        clearDoc() {
            this.delDoc = this.expDoc;
            this.expDoc = '';
        },
        //清除选中的视频
        clearVideo() {
            this.delVideo = this.expVideo;
            this.expVideo = '';
        },
        handleImage(logo) {
            let src = '';
            if (logo) {
                if (logo.indexOf('Learn') > -1) {
                    src = logo;
                } else {
                    src = `/Learn/${logo}`;
                }
            } else {
                src = this.defaultImg;
            }
            return src;
        },
        //查询课件绑定视频和课件信息
        getExpVideoOrDocList() {
            this.expVideo = '';
            this.expDoc = '';
            this.curSaveExpDoc = '';
            this.curSaveExpVideo = '';
            getVideoDetail(this.ecid)
                .then((data) => {
                    if (data.code == 1) {
                        this.videoLists = data.attribute.data;
                        let eduVideoList = this.videoLists.filter(
                            (file) => file.srctype == 'EduVideo'
                        );
                        let eduPdfList = this.videoLists.filter((file) => file.srctype == 'EduPdf');
                        if (eduVideoList.length > 0) {
                            this.curSaveExpVideo = eduVideoList[0]; //当前保存的
                            this.expVideo = eduVideoList[0]; //当前选择的
                            this.expVideo.originName = this.expVideo.srcname;
                            this.expVideo.path = this.expVideo.srcpath;
                            this.expVideo.id = this.expVideo.fileId;
                        }
                        if (eduPdfList.length > 0) {
                            this.curSaveExpDoc = eduPdfList[0]; //当前保存的
                            this.expDoc = eduPdfList[0]; //当前选择的
                            this.expDoc.originName = this.expDoc.srcname;
                            this.expDoc.path = this.expDoc.srcpath;
                            this.expDoc.id = this.expDoc.fileId;
                        }
                    } else {
                        this.expVideo = '';
                        this.expDoc = '';
                    }
                })
                .catch((err) => {
                    console.log(err);
                    this.expVideo = '';
                    this.expDoc = '';
                });
        },
        async saveExperOrDocInfo(type) {
            let formData = {
                creator: this.USER_ID,
                ecid: this.ecid,
                ispublic: 1,
                createtime: '',
                downloadtimes: 0,
                isdownload: 1,
                srclocation: 1
            };
            if (type == 'EduVideo') {
                formData.srcpath = this.expVideo.path;
                formData.srcname = this.expVideo.originName;
                formData.fileId = this.expVideo.id;
                formData.duration = this.expVideo.duration || 0;
                formData.srctype = type;
                let hasAdd = this.curSaveExpVideo && type == 'EduVideo';
                let data = await this.addOrModifyExpVideoOrDoc(hasAdd, formData, type);
                return data;
            } else if (type == 'EduPdf') {
                formData.srcpath = this.expDoc.path;
                formData.srcname = this.expDoc.originName;
                formData.fileId = this.expDoc.id;
                formData.srctype = type;
                let hasAdd = this.curSaveExpDoc && type == 'EduPdf';
                let data = await this.addOrModifyExpVideoOrDoc(hasAdd, formData, type);
                return data;
            }
        },
        addOrModifyExpVideoOrDoc(hasAdd, formData, type) {
            return new Promise((resolve) => {
                let id = '';
                if (hasAdd && type == 'EduVideo') {
                    id = this.curSaveExpVideo.srcid;
                } else if (hasAdd && type == 'EduPdf') {
                    id = this.curSaveExpDoc.srcid;
                }
                let reqApi = !hasAdd ? addExpVideo(formData) : modifyExpVideo(id, formData)
                reqApi.then((data) => {
                    if (data.code == 1) {
                        let resData = data.attribute.data;
                        if (type == 'EduVideo') {
                            this.expVideo = {...resData,...{
                                originName:resData.srcname,
                                path:resData.srcpath,
                                id:resData.fileId
                            }};
                            this.curSaveExpVideo = data.attribute.data;
                        } else if (type == 'EduPdf') {
                            this.expDoc ={...resData,...{
                                originName:resData.srcname,
                                path:resData.srcpath,
                                id:resData.fileId
                            }};
                            this.curSaveExpDoc = data.attribute.data;
                        }
                        resolve(1);
                    } else {
                        resolve(0);
                    }
                })
                .catch((err) => {
                    resolve(0);
                    console.log(err);
                });
            });
        },
        changeExpType() {
            this.expDoc = '';
            this.expVideo = '';
            this.formValidate.guide = '';
            this.useExpguideId = '';
            this.formValidate.envtempid = '';
            this.useTemplateId = '';
            this.formValidate.topology = '';
            this.useImagePath = '';
        },
        changeDirection(val) {
            if (val == 'All') {
                this.expClassifyLevel2 = this.expClassify.filter((dict) => dict.parentid);
            } else {
                this.expClassifyLevel2 = this.expClassify.filter((dict) => dict.parentid == val);
            }
            this.formValidate.type = '';
        },
        clearExpVideo() {
            return new Promise((resolve) => {
                clearExpVideo(this.ecid)
                    .then((data) => {
                        if (data.code == 1) {
                            resolve(1);
                        } else {
                            resolve(0);
                        }
                    })
                    .catch((error) => {
                        resolve(0);
                    });
            });
        },
        escape2Html(str) {
            if (!str) {
                return;
            }
            let arrEntities = { lt: '<', gt: '>', nbsp: ' ', amp: '&', quot: '"' };
            return str.replace(/&(lt|gt|amp|quot|nbsp);/gi, function(all, t) {
                return arrEntities[t];
            });
        },
        handlePublic(val) {
            let isGuide = this.guideModal
            let obj = {
                text: '',
                color: '#8d95a6'
            };
            switch (val) {
                case 'person':
                case 0:
                case '0':
                    return (obj = {
                        text: '个人',
                        color: 'rgb(255, 165, 0)'
                    });
                    break;
                case 'company':
                case 1:
                case '1':
                    return (obj = {
                        text: '单位',
                        color: 'rgb(50, 205, 50)'
                    });
                    break;
                case 'system':
                case 2:
                case '2':
                    return (obj = {
                        text:'系统',
                        color: 'rgb(65, 105, 225)'
                    });
                    break;
              case 'range':
              case 3:
              case '3':
                return obj = {
                  text:'平台',
                  color:'#ff61f4',
                }
                break;
            }
        },
        changePublic(val) {
            //          	console.log(this.useTempVisibility,this.useGuideVisibility,this.useImageVisibility,this.useExpDocVisibility,this.useExpVideoVisibility);
            if (val == 1 && this.isCreate) {
                if (this.useExpDocVisibility == 'person') {
                    this.expDoc = '';
                }
                if (this.useExpVideoVisibility == 'person') {
                    this.expVideo = '';
                }
                if (this.useGuideVisibility === 0 || this.useExpGuideVisibility == 'person') {
                    this.formValidate.guide = '';
                    this.useExpguideId = '';
                    this.guideFilePath = '';
                }
                if (this.useTempVisibility == 'person') {
                    this.formValidate.envtempid = '';
                    this.useTemplateId = '';
                }
                if (this.useImageVisibility == 'person') {
                    this.formValidate.topology = '';
                    this.useImagePath = '';
                }
            }
        },
        getDeployStatus(status) {
            this.deployStatus = status;
        },
        getProjectId(id) {
            this.prjId = id;
        },
        getExperStatus() {
            return new Promise((resolve) => {
                experStatus(this.USER_ID, this.ecid)
                    .then((res) => {
                        this.deployStatus = res.attribute.data.status;
                        this.prjId = res.attribute.data.instanceid;
                        resolve();
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            });
        },
        getReplaceTotal(total) {
            this.replaceTotal = total;
        },
        getAvaiCreateImageList() {
            return new Promise((resolve) => {
                let params = {
                    pageIndex: 1,
                    pageSize: 1,
                    projectId: this.prjId,
                    ecId: this.ecid,
                    imageStatus: 1
                };
                getCreateImageList(params)
                    .then((res) => {
                        if (res.code === 1) {
                            this.imageTotal = res.data.total;
                            resolve(this.imageTotal);
                        } else {
                            this.$Message.error({
                                content: res.message,
                                duration: 3
                            });
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            });
        },
        setEnvironStepFinishStatus() {
            this.environStepFinishStatus = true;
        },
        setQuestionStepFinishStatus() {
            this.questionStepFinishStatus = true;
        },
        // 返回课程列表
        returnCourse () {
            this.$router.push({
                name: this.$store.getters.pageName,
            })
        },
    }
};
</script>

<style scoped>
.add_icon {
  position: absolute;
  right: -23px;
  top: 8px;
  cursor: pointer;
}
.width_150{
    max-width: 150px;
    overflow: hidden;
}

.width_150.ivu-tag >>> .ivu-tag-text{
    max-width: 100px !important;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    display: inline-block;
}
.width_150.ivu-tag>>> .ivu-icon-ios-close {
    position: relative;
    top: -9px !important;
}

.flex {
  display: flex;
  align-items: center;
}
.drawer-dot {
  height: 8px;
  width: 8px;
  border-radius: 50%;
  background-color: #333;
}
.drawer-title-big {
  margin-left: 5px;
  font-size: 18px;
  font-weight: 700;
}
.drawer-title-small {
  margin-left: 15px;
  font-size: 14px;
  font-weight: bold;
}

.page-content {
  background-color: #fff;
  border-radius: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.img-header {
  display: flex;
  justify-content: space-between;
  padding: 20px 20px 0 20px;
}

.addressIcon {
  display: inline-block;
  height: 14px;
  width: 12px;
  background: url("../../../../assets/globalIcon/addressIcon.png") no-repeat
    center;
  background-size: 100% 100%;
  margin-bottom: -1px;
}

.content-wrap {
  overflow-x: hidden;
  overflow-y: auto;
  padding: 0 20px 20px;
  min-height: calc(100vh - 265px);
}

.chose-wrap {
  display: flex;
  justify-content: space-between;
  padding: 3px 8px;
  background-color: var(--table-tr-hover-color);
  align-items: center;
  margin-top: 10px;
}

.chose-name {
  /* width: calc(100% - 415px); */
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chose-s-icon {
  width: 15px;
  height: 17px;
  display: inline-block;
  margin-bottom: 1px;
  margin-right: 10px;
}

.chose-s2-icon {
  width: 13px;
  height: 15px;
  display: inline-block;
  margin-bottom: 1px;
  margin-right: 10px;
}

.deviceDrawer {
  position: relative;
}

.drawer-close {
    position: absolute;
    top: 70px;
    left: -20px;
    cursor: pointer;
}
.drawer-close img {
    width: 20px;
}
.template-select-wrapper {
}
.select-type-wrapper {
  display: flex;
  justify-content: space-between;
  height: 32px;
  /* width: 360px; */
  border: 1px solid var(--url-color) ;
}
.select-type-wrapper .type {
  flex: 1;
  text-align: center;
  border-right: 1px solid var(--url-color) ;
  color: var(--url-color) ;
  cursor: pointer;
}
.select-type-wrapper .type.current {
  background: var(--url-color);
  color: #fff;
}
.select-type-wrapper .type:last-child {
  border-right: none;
}

.select-content-wrapper {
  margin: 20px 0;
}
/deep/ .template-lable > .ivu-form-item-label::before {
  content: "*";
  display: inline-block;
  margin-right: 4px;
  line-height: 1;
  font-family: SimSun;
  font-size: 12px;
  color: #ed4014;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.ml10 {
  margin-left: 10px;
}
</style>
<style>
.deviceDrawer .ivu-drawer-body {
  overflow: inherit;
}
</style>
